package com.cjstudio.soundexample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import android.app.Activity;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class PlayWavFormatActivity extends Activity implements OnClickListener, OnTouchListener {
	
	LinearLayout root;
	Button btnPlay;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		Log.d("NRT", "onCreated: ");
		
		
		root = (LinearLayout)findViewById(R.id.LinearLayout01);
		root.setOnTouchListener(this);
		
		btnPlay = (Button)findViewById(R.id.btnPlay);
		btnPlay.setOnClickListener(this);
    }
    
    
    @Override
	public void onResume() {
		Log.d("NRT", "onResume: ");

    		super.onResume();
    		
        initSound();
            
    		_ShakeDetectionService = new ShakeDetectionService(this);
    		_ShakeDetectionService.startShakeDetection();
    }
    
    @Override
	public void onPause() {
    		_ShakeDetectionService.stopShakeDetection();
    		super.onPause();
    }

    
    ShakeDetectionService _ShakeDetectionService;

    class ShakeDetectionService extends MyShakeDetectionService {
		public ShakeDetectionService(Context mContext) {
			super(mContext);
		}
		@Override
		public void onShakeDetected() {
			Log.d("NRT", "Shake Detected!");
			playBeat();
		}
    }
    
    public void playBeat() {
    		Log.d("NRT", "PLay Beat!");
    		playSound();
    }
    
    private void initSound() { 

    	
    } 
    
    public void playSound() { 
    		Log.d("NRT", "PLay Sound!");
    		try {
				PlayShortAudioFileViaAudioTrack("/sdcard/bassdrum1_1.wav");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		
    }

	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch(arg0.getId()) {
		case R.id.btnPlay: 
			playSound();
		}
		
	}

	public boolean onTouch(View arg0, MotionEvent arg1) {
		playSound();
		// TODO Auto-generated method stub
		return false;
	}
	
	private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException {
		// We keep temporarily filePath globally as we have only two sample sounds now..
		if (filePath==null)
			return;
	
		//Reading the file..
		byte[] byteData = null; 
		File file = null; 
		file = new File(filePath); // for ex. path= "/sdcard/samplesound.pcm" or "/sdcard/samplesound.wav"
//		InputStream in = getResources().openRawResource(R.raw.bassdrum1);
		byteData = new byte[(int) file.length()];
		/*
		int length = 0;
		long skip = 0L;
		
		do {
			skip = in.skip(Long.MAX_VALUE);
			length += skip;
		} while (skip > 0L);
		in = getResources().openRawResource(R.raw.bassdrum1); // reset the stream
	
		byteData = new byte[length];*/
		FileInputStream in = null;
		try {
			in = new FileInputStream( file );
			in.read( byteData );
			in.close(); 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Set and push to audio track..
		int intSize = android.media.AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT); 
		AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, intSize, AudioTrack.MODE_STREAM); 
		if (at!=null) { 
			at.play();
			// Write the byte array to the track
			at.write(byteData, 0, byteData.length); 
			at.stop();
			at.release();
		}
		else
			Log.d("TCAudio", "audio track is not initialised ");
	}
	
	
}